package com.mzba.zxdlyllp;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.mzba.zxdlyllp.utils.ActivityManagerUtil;
import com.mzba.zxdlyllp.utils.AppContext;
import com.mzba.zxdlyllp.utils.BasicUIEvent;
import com.mzba.zxdlyllp.utils.CommandTaskEvent;
import com.mzba.zxdlyllp.widget.CustomDialog;

/**
 * Basic Activity,all the Activity should extends this Activity
 * @author 06peng
 * 
 */
public class BasicActivity extends SherlockFragmentActivity implements BasicUIEvent {
	public ActionBar actionBar;
	public static final int DESTROYDIALOG = 0x00000101;
	private final static int cancelAlertDialog = 0x00000102;
	private final static int destroyDialogByFinish = 0x00000103;
	public CustomDialog dialog;
	protected Toast toast;
	public int CanvasHeight;
	public int CanvasWidth;
	

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		AppContext.setContext(this);
		setTheme(R.style.Theme_Sherlock);
		initActionBar();
		ActivityManagerUtil.addActivity(this);
		DisplayMetrics displayMetrics = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		CanvasWidth = displayMetrics.widthPixels;
		CanvasHeight = displayMetrics.heightPixels;
		initActionBar();
	}
	
	private void initActionBar(){
		actionBar = getSupportActionBar();
		actionBar.hide();
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	
	@Override
	protected void onDestroy() {
		if (toast != null) {
			toast.cancel();
		}
		super.onDestroy();
	}

	protected boolean onBackClick() {
		finish();
		return false;
	}

	public View getLayoutView(int layout) {
		return LayoutInflater.from(this).inflate(layout, null);
	}

	@Override
	public void execute(int mes, Object obj) {

	}

	public void eventTask(int CommandID, String tips, Object obj, boolean showDailog) {
		try {
			CommandTaskEvent com = new CommandTaskEvent(this, this, showDailog);
			com.execute((new Object[] { CommandID + "", obj }));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public AlertDialog alert = null;
	public boolean alertIsShow = false;

	public void loading() {
		try {
			if (this.isFinishing()) {
				return;
			}
			if (dialog == null || !dialog.isShowing()) {
				View progressview = LayoutInflater.from(BasicActivity.this).inflate(R.layout.progress_dialog, null);
				CustomDialog.Builder progressBuilder = new CustomDialog.Builder(BasicActivity.this);
				progressBuilder.setContentView(progressview);
				dialog = progressBuilder.create();
				dialog.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void destroyDialog() {
		basicHandler.sendEmptyMessage(DESTROYDIALOG);
	}

	public void onToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
	}

	/**
	 * 系统信息 必须在handler或者控件触发 调用才有效
	 * 
	 * @param message
	 */
	@SuppressWarnings("deprecation")
	public void setSysMes(String message) {
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		if (alert == null)
			alert = new AlertDialog.Builder(this).create();

		if (!alert.isShowing()) {
			alertIsShow = true;
			alert.setTitle(getString(R.string.system_info));
			alert.setMessage(message);
			alert.setButton(getString(R.string.confirm_ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							alertIsShow = false;
						}
					});
			alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					alertIsShow = false;
				}
			});
			alert.show();

		}
	}

	/**
	 * 系统信息 必须在handler或者控件触发 调用才有效
	 * 
	 * @param message
	 */
	@SuppressWarnings("deprecation")
	public void setSysMes(String message, final int what) {
		if (message == null || "出错了".equals(message)) {
			return;
		}
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		if (alert == null)
			alert = new AlertDialog.Builder(this).create();

		if (!alertIsShow) {
			alertIsShow = true;
			alert.setTitle(getString(R.string.system_info));
			alert.setMessage(message);
			alert.setButton(getString(R.string.confirm_ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							sysMesPositiveButtonEvent(what);
							alertIsShow = false;
						}
					});
			alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					alertIsShow = false;
				}
			});
			alert.show();
		}
	}

	/**
	 * dismiss alert 系统信息提示框
	 */
	public void cancelAlertDialog() {
		if (alert != null && alert.isShowing()) {
			Message localMessage = Message.obtain(basicHandler, cancelAlertDialog);
			basicHandler.sendMessage(localMessage);
		}
	}

	/**
	 * 系统信息选择提示 必须在handler或者控件触发 调用才有效
	 * 
	 * @param message
	 * @param what
	 */
	public void showChoseMes(String message, final int what) {
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		Builder alert = new AlertDialog.Builder(this); // 为了避免 setSysMes（String
														// message,final int
														// what） 出现 “否”选择
		if (!alertIsShow) {
			alertIsShow = true;
			alert.setTitle(getString(R.string.system_info));
			alert.setMessage(message);
			alert.setPositiveButton(getString(R.string.confirm_yes),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							sysMesPositiveButtonEvent(what);
							alertIsShow = false;
						}
					});
			alert.setNegativeButton(getString(R.string.confirm_no),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							sysMesNegativeButtonEvent(what);
							alertIsShow = false;
						}
					});
			alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
				public void onCancel(DialogInterface dialog) {
					sysMesOnCancelEvent(what);
					alertIsShow = false;
				}
			});
			alert.show();
		}
	}

	/**
	 * 系统信息提示ok按钮回调方法 是 showChoseMes(String message,final int
	 * what)，setSysMes(String message,final int what)方法回调
	 */
	public void sysMesPositiveButtonEvent(int what) {

	}

	/**
	 * 系统信息提示no按钮回调方法 是 showChoseMes(String message,final int what)方法回调
	 * 
	 * @param what
	 */
	public void sysMesNegativeButtonEvent(int what) {

	}

	/**
	 * 系统信息提示no按钮回调方法 是 showChoseMes(String message,final int what)方法回调
	 * 
	 * @param what
	 */
	public void sysMesOnCancelEvent(int what) {

	}

	public void destroyDialogByFinish() {
		Message localMessage = Message.obtain(basicHandler, destroyDialogByFinish);
		basicHandler.sendMessage(localMessage);
	}

	public void finish() {
		try {
			if (dialog != null && dialog.isShowing()) {
				destroyDialogByFinish();
			} else {
				super.finish();
			}
//			ActivityManager.removeActivity(this);
			System.gc();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void finishAll() {
		try {
			if (dialog != null && dialog.isShowing()) {
				destroyDialogByFinish();
			} else {
				super.finish();
			}
			System.gc();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 选择菜单 弹出框
	 * @param choices 显示的菜单
	 * @param chooseType 菜单的类型，为了区别其他菜单
	 */
	public void chooseAction(String[] choices, final int chooseType) {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
	
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, choices);

		final AlertDialog.Builder builder = new AlertDialog.Builder(
				dialogContext);
		builder.setTitle(R.string.system_info);
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						doSelectChooseEvent(which, chooseType);
					}
				});
		builder.create().show();
	}
	
	public void doSelectChooseEvent(int which, int chooseType) {
		
	}

	public Handler basicHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DESTROYDIALOG:
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				break;
			case cancelAlertDialog:
				if (alert != null && alert.isShowing()) {
					alert.cancel();
				}
				break;
			case destroyDialogByFinish:
				if (dialog != null && dialog.isShowing()) {
					dialog.cancel();
				}
				BasicActivity.this.finish();
				break;
			default:
				break;
			}
		}
	};
	
	
	public boolean getGpsState(Context context) {
		if (null == context)
			return false;
		LocationManager alm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		return alm.isProviderEnabled(LocationManager.GPS_PROVIDER);

	}

	public void toggleGPS() {
		Intent gpsIntent = new Intent();
		gpsIntent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
		gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
		gpsIntent.setData(Uri.parse("custom:3"));
		try {
			PendingIntent.getBroadcast(this, 0, gpsIntent, 0).send();
		} catch (CanceledException e) {
			e.printStackTrace();
		}
	}
	
}
